package com.bianqian.demo.controller;

import com.bianqian.demo.dto.*;
import com.bianqian.demo.entity.User;
import com.bianqian.demo.service.UserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.Optional;

/**
 * 用户信息控制器
 */
@RestController
@RequestMapping("/api/user")
@RequiredArgsConstructor
@Slf4j
@Validated
public class UserController {
    
    private final UserService userService;
    
    /**
     * 获取用户信息
     * @param request HTTP请求
     * @return 用户信息
     */
    @GetMapping("/profile")
    public ApiResponse<UserProfileDto> getUserProfile(HttpServletRequest request) {
        try {
            Long userId = (Long) request.getAttribute("userId");
            log.info("获取用户信息请求，用户ID：{}", userId);
            
            Optional<User> userOpt = userService.findById(userId);
            if (!userOpt.isPresent()) {
                log.warn("用户不存在，ID：{}", userId);
                return ApiResponse.error("用户不存在");
            }
            
            User user = userOpt.get();
            log.info("找到用户信息 - ID: {}, 账号: {}, 昵称: {}, 手机号: {}", 
                    user.getId(), user.getAccount(), user.getNickname(), user.getPhone());
            
            UserProfileDto userProfile = new UserProfileDto(
                user.getId(),
                user.getAccount(),
                user.getNickname(),
                user.getPhone(),
                user.getAvatar(),
                user.getCreatedAt(),
                user.getUpdatedAt()
            );
            
            log.info("用户信息获取成功，ID：{}, 返回的手机号：{}", userId, userProfile.getPhone());
            return ApiResponse.success("获取成功", userProfile);
            
        } catch (Exception e) {
            log.error("获取用户信息异常：", e);
            return ApiResponse.error("获取用户信息失败，请重试");
        }
    }
    
    /**
     * 更新用户信息
     * @param request HTTP请求
     * @param updateRequest 更新请求
     * @return 更新后的用户信息
     */
    @PutMapping("/profile")
    public ApiResponse<UserProfileDto> updateUserProfile(HttpServletRequest request, 
                                                         @Valid @RequestBody UpdateUserProfileRequest updateRequest) {
        try {
            Long userId = (Long) request.getAttribute("userId");
            log.info("更新用户信息请求，用户ID：{}", userId);
            
            User updatedUser = userService.updateProfile(
                userId,
                updateRequest.getNickname(),
                updateRequest.getPhone(),
                updateRequest.getAvatar(),
                updateRequest.getInsurancePassword()
            );
            
            UserProfileDto userProfile = new UserProfileDto(
                updatedUser.getId(),
                updatedUser.getAccount(),
                updatedUser.getNickname(),
                updatedUser.getPhone(),
                updatedUser.getAvatar(),
                updatedUser.getCreatedAt(),
                updatedUser.getUpdatedAt()
            );
            
            log.info("用户信息更新成功，ID：{}，是否更新保险箱密码：{}", userId, updateRequest.getInsurancePassword() != null);
            return ApiResponse.success("更新成功", userProfile);
            
        } catch (RuntimeException e) {
            log.error("更新用户信息失败：{}", e.getMessage());
            return ApiResponse.error(e.getMessage());
        } catch (Exception e) {
            log.error("更新用户信息异常：", e);
            return ApiResponse.error("更新用户信息失败，请重试");
        }
    }
    
    /**
     * 注销账号
     * @param request HTTP请求
     * @return 注销结果
     */
    @DeleteMapping("/delete")
    public ApiResponse<Object> deleteAccount(HttpServletRequest request) {
        try {
            Long userId = (Long) request.getAttribute("userId");
            log.info("注销账号请求，用户ID：{}", userId);
            
            userService.deleteUser(userId);
            
            log.info("账号注销成功，ID：{}", userId);
            return ApiResponse.success("账号已注销", null);
            
        } catch (RuntimeException e) {
            log.error("注销账号失败：{}", e.getMessage());
            return ApiResponse.error(e.getMessage());
        } catch (Exception e) {
            log.error("注销账号异常：", e);
            return ApiResponse.error("注销账号失败，请重试");
        }
    }

    /**
     * 设置保险箱密码（独立接口）
     */
    @PostMapping("/insurance/password")
    public ApiResponse<Object> setInsurancePassword(HttpServletRequest request,
                                                    @Valid @RequestBody SetInsurancePasswordRequest body) {
        try {
            Long userId = (Long) request.getAttribute("userId");
            userService.setInsurancePassword(userId, body.getPassword());
            return ApiResponse.success("保险箱密码已更新", null);
        } catch (RuntimeException e) {
            return ApiResponse.error(e.getMessage());
        } catch (Exception e) {
            return ApiResponse.error("设置失败，请重试");
        }
    }
}
